<template>
  <div class="network-graph-selector">
    <!-- 图形库选择 -->
    <a-card size="small" class="selector-card">
      <template #title>
        <a-space>
          <experiment-outlined />
          可视化引擎
        </a-space>
      </template>
      
      <a-radio-group 
        v-model:value="selectedLibrary" 
        @change="handleLibraryChange"
        button-style="solid"
        size="small"
      >
        <a-radio-button value="echarts">
          <a-space>
            <bar-chart-outlined />
            ECharts
          </a-space>
        </a-radio-button>
        <a-radio-button value="g6">
          <a-space>
            <node-index-outlined />
            G6
          </a-space>
        </a-radio-button>
      </a-radio-group>
      
      <div class="library-description">
        <a-typography-text type="secondary" :style="{ fontSize: '12px' }">
          {{ getLibraryDescription(selectedLibrary) }}
        </a-typography-text>
      </div>
    </a-card>

    <!-- 网络图组件 -->
    <div class="graph-wrapper">
      <component
        :is="currentGraphComponent"
        ref="graphRef"
        :data="data"
        :width="width"
        :height="height"
        v-bind="$attrs"
        @node-click="$emit('nodeClick', $event)"
        @edge-click="$emit('edgeClick', $event)"
        @node-double-click="$emit('nodeDoubleClick', $event)"
        @canvas-click="$emit('canvasClick')"
      />
    </div>

    <!-- 性能监控 -->
    <a-card v-if="showPerformanceMonitor" size="small" class="performance-card">
      <template #title>
        <a-space>
          <dashboard-outlined />
          性能监控
        </a-space>
      </template>
      
      <a-row :gutter="8">
        <a-col :span="8">
          <a-statistic
            title="渲染时间"
            :value="performanceMetrics.renderTime"
            suffix="ms"
            :value-style="{ fontSize: '12px' }"
          />
        </a-col>
        <a-col :span="8">
          <a-statistic
            title="内存使用"
            :value="performanceMetrics.memoryUsage"
            suffix="MB"
            :value-style="{ fontSize: '12px' }"
          />
        </a-col>
        <a-col :span="8">
          <a-statistic
            title="FPS"
            :value="performanceMetrics.fps"
            :value-style="{ fontSize: '12px' }"
          />
        </a-col>
      </a-row>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
  ExperimentOutlined,
  BarChartOutlined,
  NodeIndexOutlined,
  DashboardOutlined
} from '@ant-design/icons-vue'
import EChartsNetworkGraph from './EChartsNetworkGraph.vue'
import G6NetworkGraph from './G6NetworkGraph.vue'
import type { NetworkVisualizationData } from '@/api/types'

interface Props {
  data: NetworkVisualizationData
  width?: number
  height?: number
  defaultLibrary?: 'echarts' | 'g6'
  showPerformanceMonitor?: boolean
}

interface Emits {
  (e: 'nodeClick', node: any): void
  (e: 'edgeClick', edge: any): void
  (e: 'nodeDoubleClick', node: any): void
  (e: 'canvasClick'): void
  (e: 'libraryChange', library: string): void
}

const props = withDefaults(defineProps<Props>(), {
  width: 800,
  height: 600,
  defaultLibrary: 'echarts',
  showPerformanceMonitor: false
})

const emit = defineEmits<Emits>()

// 响应式数据
const selectedLibrary = ref(props.defaultLibrary)
const graphRef = ref()
const performanceMetrics = ref({
  renderTime: 0,
  memoryUsage: 0,
  fps: 60
})

// 计算属性
const currentGraphComponent = computed(() => {
  return selectedLibrary.value === 'echarts' ? EChartsNetworkGraph : G6NetworkGraph
})

// 方法
const handleLibraryChange = (e: any) => {
  const library = e.target.value
  selectedLibrary.value = library
  
  // 记录切换时间用于性能监控
  const startTime = performance.now()
  
  // 延迟一帧确保组件已切换
  requestAnimationFrame(() => {
    const endTime = performance.now()
    performanceMetrics.value.renderTime = Math.round(endTime - startTime)
    
    message.success(`已切换到 ${getLibraryDisplayName(library)} 引擎`)
    emit('libraryChange', library)
  })
}

const getLibraryDescription = (library: string): string => {
  const descriptions = {
    echarts: '基于Canvas的图表库，适合大数据量展示和统计图表',
    g6: '专业的图可视化引擎，提供丰富的交互和布局算法'
  }
  return descriptions[library as keyof typeof descriptions] || ''
}

const getLibraryDisplayName = (library: string): string => {
  const names = {
    echarts: 'ECharts',
    g6: 'G6'
  }
  return names[library as keyof typeof names] || library
}

// 性能监控
const startPerformanceMonitoring = () => {
  if (!props.showPerformanceMonitor) return

  let frameCount = 0
  let lastTime = performance.now()

  const updateFPS = () => {
    frameCount++
    const currentTime = performance.now()
    
    if (currentTime - lastTime >= 1000) {
      performanceMetrics.value.fps = Math.round((frameCount * 1000) / (currentTime - lastTime))
      frameCount = 0
      lastTime = currentTime
    }
    
    requestAnimationFrame(updateFPS)
  }

  updateFPS()

  // 监控内存使用（如果浏览器支持）
  if ('memory' in performance) {
    const updateMemory = () => {
      const memory = (performance as any).memory
      if (memory) {
        performanceMetrics.value.memoryUsage = Math.round(memory.usedJSHeapSize / 1024 / 1024)
      }
    }
    
    updateMemory()
    setInterval(updateMemory, 2000) // 每2秒更新一次内存使用
  }
}

// 暴露方法给父组件
const getGraphInstance = () => {
  return graphRef.value?.getGraph?.() || graphRef.value?.getChart?.()
}

const zoomIn = () => {
  graphRef.value?.zoomIn?.()
}

const zoomOut = () => {
  graphRef.value?.zoomOut?.()
}

const fitView = () => {
  graphRef.value?.fitView?.()
}

const changeLayout = (layout: string) => {
  graphRef.value?.changeLayout?.(layout)
}

// 监听数据变化，更新渲染时间
watch(() => props.data, () => {
  if (props.showPerformanceMonitor) {
    const startTime = performance.now()
    
    requestAnimationFrame(() => {
      const endTime = performance.now()
      performanceMetrics.value.renderTime = Math.round(endTime - startTime)
    })
  }
}, { deep: true })

onMounted(() => {
  if (props.showPerformanceMonitor) {
    startPerformanceMonitoring()
  }
})

defineExpose({
  getGraphInstance,
  zoomIn,
  zoomOut,
  fitView,
  changeLayout,
  selectedLibrary: () => selectedLibrary.value
})
</script>

<style scoped>
.network-graph-selector {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.selector-card {
  flex-shrink: 0;
}

.library-description {
  margin-top: 8px;
  min-height: 32px;
}

.graph-wrapper {
  flex: 1;
  min-height: 400px;
}

.performance-card {
  flex-shrink: 0;
}

:deep(.ant-card-head-title) {
  font-size: 14px;
}

:deep(.ant-card-body) {
  padding: 12px;
}

:deep(.ant-radio-button-wrapper) {
  display: flex;
  align-items: center;
  gap: 4px;
}

:deep(.ant-statistic-title) {
  font-size: 11px;
  margin-bottom: 2px;
}

:deep(.ant-statistic-content) {
  font-size: 12px;
}

@media (max-width: 768px) {
  .network-graph-selector {
    gap: 12px;
  }
  
  .graph-wrapper {
    min-height: 300px;
  }
}
</style>